    import getIn from '../yali-sdk/utils/getIn';
import { SUCCESS } from '../yali-sdk/utils/success';
import apiAuthorize from '../yali-sdk/business/live/api/apiAuthorize';
import { FAIL } from '../yali-sdk/utils/fail';
import { filterImg } from '../pages/imgBaseUrl';
import apiLiveSet from '../yali-sdk/business/live/api/apiLiveSet';
import getConfig from "../config";
let yali_userinfo,
    yali_live_setting;
// 根据微信code码获取鸭梨用户信息

export const CODE_LOGIN_ERROR = -1;
export const CODE_NO_USER = -2;
let _actionDispatcher;
// 初始化函数，不使用全局actionDispatcher，污染大
export function init(actionDispatcher) {
    _actionDispatcher = actionDispatcher;
}

export const getYaliLiveSetting = id => new Promise((rs, rj) => {
    if (yali_live_setting) {
        rs && rs(yali_live_setting);
    }
    _actionDispatcher && _actionDispatcher.execute(apiLiveSet, { id, version: getConfig().version }, (f, fs) => {
        if (f === SUCCESS && getIn(fs, ['data'])) {
            yali_live_setting = getIn(fs, ['data']);
            rs && rs(yali_live_setting);
        } else if (f === FAIL) {
            rj && rj();
        }
    });
});
export const getExtConfig = () => (false && wx.getExtConfigSync ? wx.getExtConfigSync() : { extAppid: getConfig().wxAppid});
// 获取直播个人信息
export const getYaliUserInfo = (option = {}) => new Promise((resolve, reject) => {
    // 读本地缓存
    // console.log(yali_userinfo, yali_live_setting)
    if (yali_userinfo && !option.forceRefresh) {
        resolve && resolve(yali_userinfo);
        return;
    }
    const appid = getIn(getExtConfig(), ['extAppid']);
    wx.login({
      success: (res) => {
      
            _actionDispatcher && _actionDispatcher.execute(apiAuthorize, {code: res.code,appid,
            }, (f, fs) => {
                if (f === SUCCESS) {
                    yali_userinfo = getIn(fs, ['data', 'user']);
                    if (yali_userinfo) {
                        filterImg(yali_userinfo, 'head_photo');
                        // yali_live_setting = getIn(fs, ['data', 'ret']);
                        resolve && resolve(yali_userinfo);
                    } else {
                        reject && reject(CODE_NO_USER);
                    }
                } else if (f === FAIL) {
                    // 查找不到用户信息，走注册流程或者其他业务
                    reject && reject(CODE_NO_USER);
                }
            });
        },
        fail: (res) => {
            console.log('wx login error', res);
            reject && reject(CODE_LOGIN_ERROR);
        },
    });
});
// 检查微信授权情况， 在必须获取到用户信息的情况下才调用。
export const checkWxAuthorize = () => new Promise((resolve, reject) => {
    wx.getUserInfo({
        success: (res) => {
            resolve && resolve(res);
        },
        fail: () => {
            wx.showModal({
                content: '您未开启授权，是否前往授权',
                confirmText: '授权',
                success: () => {
                    wx.openSetting();
                },
            });
        },
    });
});

